<template>
  <div class="app-container">
    <el-form ref="queryForm" :inline="true">
      <el-form-item :label="$t('area.Layer')" prop="postName">
        <treeselect
          v-model="mapId"
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :max-height="600"
          :options="mapTreeData"
          :default-expand-level="1"
          @input="nodeClick"
        />
      </el-form-item>
      <el-form-item :label="$t('history.date')" prop="postName">
        <el-date-picker
          v-model="timeValue1"
          type="datetime"
          :placeholder="$t('operating.StartTime')"
          size="small"
          @change="change1"
        />
        -
        <el-date-picker
          v-model="timeValue2"
          type="datetime"
          :placeholder="$t('operating.EndTime')"
          size="small"
          @change="change2"
        />
      </el-form-item>
      <el-form-item :label="$t('history.deptname')" prop="postName">
        {{ deptValue }}
        <treeselect
          v-model="deptValue"
          size="small"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :max-height="600"
          :options="depts"
          :default-expand-level="1"
          @input="getFilterObjData"
        />
      </el-form-item>
      <el-form-item :label="$t('history.objValue')" prop="postName">
        {{ model }}
        <el-select
          v-model="model"
          size="small"
          :clearable="true"
          :placeholder="$t('operating.pleaseChosen')"
          filterable
        >
          <el-option
            v-for="item in modelCount"
            :key="item.idx"
            :label="item.name"
            :value="item.resourceId"
          />
        </el-select>
      </el-form-item>

      <!-- <el-form-item :label="$t('history.deptname')" prop="postCode">
        <treeselect
          v-model="queryParams.param.deptValue"
          :placeholder="$t('operating.pleaseChosen')"
          :show-count="true"
          :maxHeight="600"
          :options="depData"
          :default-expand-level="1"
          @input="nodeClick"
          style="width: 150px; margin-right: 10px"
        >
        </treeselect>
      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="query"
        >{{ $t("operating.search") }}</el-button>
        <el-button
          v-hasPermi="['system:report:reportAlarm']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="exportTrack"
        >{{ $t("operating.export") }}
        </el-button>
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{
            $t("operating.reset")
          }}</el-button> -->
      </el-form-item>
    </el-form>
    <!-- <el-header>

        <div class="handle-box">
          <span>{{$t('area.Layer')}}:</span>
          <treeselect v-model="mapId"
                      :placeholder="$t('operating.pleaseChosen')"
                      :show-count="true"
                      :maxHeight="600"
                      :options="mapTreeData"
                      :default-expand-level="1"
                      @input="nodeClick">
          </treeselect>
          <span>{{$t('history.deptname')}}:</span>
          <treeselect v-model="deptValue"
                      :placeholder="$t('operating.pleaseChosen')"
                      :show-count="true"
                      :maxHeight="600"
                      :options="depts"
                      :default-expand-level="1"
                      @input="getFilterObjData">
          </treeselect>

          <span>{{$t('history.objValue')}}:</span>
          <el-select v-model="model"
                     :clearable="true"
                     :placeholder="$t('operating.pleaseChosen')"
                     filterable
                     style="width:140px;">
            <el-option v-for="item in modelCount"
                       :key="item.idx"
                       :label="item.name"
                       :value="item.resourceId"></el-option>
          </el-select>
          <span>{{$t('history.date')}}:</span>
          <el-date-picker v-model="timeValue1"
                          type="datetime"
                          @change="change1"
                          :placeholder="$t('operating.StartTime')"
                          style="width:200px;">
          </el-date-picker>
          <el-date-picker v-model="timeValue2"
                          type="datetime"
                          @change="change2"
                          :placeholder="$t('operating.EndTime')"
                          style="width:200px;">
          </el-date-picker>
          <span>
            <el-button icon="el-icon-search"
                       @click="query"
                       style="background-color:#f1a11e; color: #fff;">{{ $t('operating.search')}}</el-button>
          </span>
        </div>
      </el-header> -->
    <div class="context">
      <div id="map" />
      <div class="bottom_progress">
        <div>
          <div style="width:30px;height:30px;float:left;margin-right:30px">
            <el-button
              class="playbtn"
              type="primary"
              icon="al-icon-carplay"
              size="mini"
              circle
              @click="clickPlayBtn"
            />
          </div>
          <div style="float:left;" @mousedown="progressUIValue">
            <el-slider
              v-model="progressIndex"
              style="width:400px;"
              :max="posLength"
              :step="1"
              :format-tooltip="formatTooltip"
              @change="progressValueChange"
            />
          </div>
          <div style="float:left;margin-left:30px">
            <el-select v-model="temp">
              <el-option
                v-for="item in tempCount"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
        </div>
      </div>
    </div>

    <!-- 左下角坐标显示和缩放比例 -->
    <div class="positiondiv">
      <span />
    </div>
    <div class="scalediv">
      <span />
    </div>
  </div>
</template>

<script>
import i18n from '@/utils/lang/index'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  sendThis,
  Load_Map,
  _iMap,
  _TransPixel,
  TagStyle,
  _Style,
  updateOverlayPosition,
  FenceStyle,
  _TransMetric,
  _TransMetricFence,
  _dPR
} from '@/utils/historyMap.js'
import { downloadFile } from '@/api/cy.js'
import {
  webSockUrl,
  webSockStatisticsUrl,
  cameraServerUrl,
  baseUrl,
  initPicPath,
  webSockMonitorUrl,
  rateHeartShow
} from '@/utils/global'
import { Vector as VectorSource } from 'ol/source.js'
import { Vector as VectorLayer } from 'ol/layer.js'
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
import { LineString } from 'ol/geom.js'
import { Style, Stroke } from 'ol/style.js'
import { listDept } from '@/api/system/dept'
import { getMapTree, getMap } from '@/api/location'

import {
  getDeptTree,
  getDeptDetail,
  getAllDeptDetail,
  getHistoryInfoDetail
} from '@/api/system/historyDisplayInfo.js'

import { treeselect } from '@/api/system/dept'

export default {
  components: { Treeselect },
  data() {
    return {
      mapId: '',
      oldMapId: null,
      mapTreeData: [],
      radio: '1',
      timeValue1: new Date(new Date().getTime() - 1000 * 60 * 30),
      timeValue2: new Date(),
      model: '',
      modelCount: [],
      TagSource: null,
      TagLayer: null,
      lineSource: null,
      lineLayer: null,
      temp: 100,
      trackData: [],
      currentPos: 1,
      feature_: null,
      setTImeOut_: null,
      tempCount: [
        {
          value: 50,
          label: '16x'
        },
        {
          value: 100,
          label: '8x'
        },
        {
          value: 200,
          label: '4x'
        },
        {
          value: 400,
          label: '2x'
        }
      ],
      posLength: 0,
      rloading: [],
      depts: [],
      deptValue: null,
      progressIndex: 0
    }
  },
  mounted() {
    this.initData()
    this.getDeptList()

    // // 刚打开时，部门默认不选择，此时，人员应该显示所有
    getAllDeptDetail().then(res => {
      const RES = this.responseUse(res)
      this.modelCount = RES
    })
  },
  beforeDestroy() {
    clearTimeout(this.setTImeOut_)
  },
  methods: {
    initData() {
      // 加载地图树
      getMapTree().then(res => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.mapTreeData = RES
          sendThis(this)
          this.mapId = RES[0].id
        }
      })
    },
    nodeClick() {
      if (this.oldMapId == this.mapId) {
        this.$message({
          message: i18n.t('realtime.areaQequired'),
          type: 'warning'
        })
      } else if (this.mapId !== undefined) {
        this.oldMapId = this.mapId
        getMap(this.mapId).then(res => {
          const RES = this.responseUse(res)
          if (RES != undefined) {
            $('#map').empty()
            Load_Map(
              baseUrl + '/file' + RES.mapPath,
              RES.mapActualX,
              RES.mapActualY,
              RES.mapPixelX,
              RES.mapPixelY,
              RES.mapPixelX / RES.mapActualX,
              [RES.mapOriginX, RES.mapOriginY],
              false
            )
            this.loadLayer()
          }
        })
      }
    },
    // 切换部门时，更新对象数据
    getFilterObjData(val) {
      // 把部门对象选择框清空掉
      if (val != undefined) {
        // 选择有部门
        getDeptDetail(val).then(res => {
          const RES = this.responseUse(res)
          this.modelCount = RES
          this.model = ''
        })
      } else {
        getAllDeptDetail().then(res => {
          const RES = this.responseUse(res)
          this.modelCount = RES
          this.model = ''
        })
      }
    },
    //  获取部门列表
    getDeptList() {
      // getDeptTree().then((res) => {
      //   const RES = this.responseUse(res)
      //   if (typeof RES !== 'undefined') {
      //     this.depts = RES
      //   }
      // });
      treeselect().then(res => {
        const RES = this.responseUse(res)
        if (typeof RES !== 'undefined') {
          this.depts = this.handleTree(RES, 'deptId')
        }
      })
      // getDeptTree().then((res) => {
      //   const RES = this.responseUse(res)
      //   if (typeof RES !== 'undefined') {
      //     this.depts = RES
      //   }
      // })
    },
    change1() {
      if (this.timeValue1 > this.timeValue2) {
        var tt = this.timeValue1.getTime()
        var ntt = tt + 1000 * 60 * 120
        this.timeValue2 = new Date(ntt)
      }
    },
    change2() {
      if (this.timeValue2 < this.timeValue1) {
        var tt = this.timeValue2.getTime()
        var ntt = tt - 1000 * 60 * 120
        this.timeValue1 = new Date(ntt)
      }
    },
    query() {
      if (this.mapId == '' || this.model == '') {
        this.$message({
          message: i18n.t('Notice.selectLayerOrQueryObject')
        })
        return
      }
      // this.rloading = this.$loading({
      //   lock: true,
      //   text: i18n.t('areaTrackPlayback.loading'),
      //   spinner: 'el-icon-loading',
      //   background: 'rgba(0,0,0,0.7)'
      // })
      clearTimeout(this.setTImeOut_)
      this.currentPos = 0
      this.lineSource.clear(true)
      this.TagSource.clear(true)

      var startTime = this.v_FormatDateTime(
        new Date(this.timeValue1).getTime()
      )
      var endTime = this.v_FormatDateTime(new Date(this.timeValue2).getTime())
      var param = {
        mapId: this.mapId,
        resourceId: this.model,
        startTime: startTime,
        endTime: endTime
      }
      getHistoryInfoDetail(param).then(res => {
        // this.rloading.close()
        const RES = this.responseUse(res)
        if (undefined != RES && RES.length > 0) {
          var point = new Point(_TransPixel([RES[0].posX, RES[0].posY]))
          this.feature_ = new Feature(point)
          this.feature_.set('type', RES[0].type)
          this.feature_.set('name', RES[0].resourceName)
          this.feature_.set('visible', true)
          this.feature_.set('workTypeName', RES[0].workTypeName)
          this.feature_.setId(RES[0].tagId)
          this.TagSource.addFeature(this.feature_)
          this.trackData = RES
          this.posLength = RES.length
          $('.playbtn i').attr('class', 'al-icon-carpause')
          this.drawLine()
        } else {
          this.$message({
            message: i18n.t('operating.switchQuery')
          })
        }
      })
    },
    // 加载地位图层和线图层,
    loadLayer() {
      this.TagSource = new VectorSource({
        wrapX: false
      })
      this.TagLayer = new VectorLayer({
        source: this.TagSource,
        style: function(feature) {
          return TagStyle(feature, 0)
        }
      })
      this.lineSource = new VectorSource({
        wrapX: false
      })
      this.lineLayer = new VectorLayer({
        source: this.lineSource,
        style: new Style({
          stroke: new Stroke({
            color: 'green',
            width: 3
          })
        })
      })
      _iMap.addLayer(this.lineLayer)
      _iMap.addLayer(this.TagLayer)
    },
    // 定时画线，定时更新点位位置
    drawLine() {
      var self = this
      self.progressIndex = self.currentPos
      if (self.currentPos > self.posLength || self.posLength == 0) {
        return
      }
      if (
        self.currentPos == self.posLength ||
        self.currentPos == self.posLength - 1
      ) {
        // 点位移动
        var from = _TransPixel([
          self.trackData[self.posLength - 1].posX,
          self.trackData[self.posLength - 1].posY
        ])

        self.feature_.getGeometry().setCoordinates(from)
      } else {
        var from = _TransPixel([
          self.trackData[self.currentPos].posX,
          self.trackData[self.currentPos].posY
        ])
        var to = _TransPixel([
          self.trackData[self.currentPos + 1].posX,
          self.trackData[self.currentPos + 1].posY
        ])
        // 点位移动
        self.feature_.getGeometry().setCoordinates(to)
        // 画线
        var lineFeature = new Feature(new LineString([from, to]))
        self.lineSource.addFeature(lineFeature)
      }
      self.currentPos++
      self.setTImeOut_ = setTimeout(function() {
        self.drawLine()
      }, self.temp)
    },
    progressValueChange(val) {
      this.currentPos = val
      this.lineSource.clear(true)
      if (this.posLength != 0) {
        $('.playbtn i').attr('class', 'al-icon-carpause')
      }
      this.drawLine()
    },
    progressUIValue() {
      $('.playbtn i').attr('class', 'al-icon-carplay')
      clearTimeout(this.setTImeOut_)
    },
    clickPlayBtn() {
      const className = $('.playbtn i').attr('class')
      if (className === 'al-icon-carplay') {
        // 处于暂定状态
        $('.playbtn i').attr('class', 'al-icon-carpause')
        this.drawLine()
      } else if (className === 'al-icon-carpause') {
        // 处于播放状态
        $('.playbtn i').attr('class', 'al-icon-carplay')
        clearTimeout(this.setTImeOut_)
      }
    },
    formatTooltip(val) {
      if (this.posLength != 0) {
        if (
          this.currentPos == this.posLength ||
          this.currentPos > this.posLength
        ) {
          return this.trackData[this.posLength - 1].speed
        } else {
          return this.trackData[this.currentPos].speed
        }
      }
    },
    exportTrack() {
      if (this.mapId == '' || this.mapId == undefined) {
        this.$message({
          message: i18n.t('Notice.selectLayerOrQueryObject')
        })
        return
      }
      const startTime = this.v_FormatDateTime(
        new Date(this.timeValue1).getTime()
      )
      const endTime = this.v_FormatDateTime(
        new Date(this.timeValue2).getTime()
      )

      const queryParams = {
        mapId: this.mapId,
        model: this.model,
        deptValue: this.deptValue,
        startTime: startTime,
        endTime: endTime

      }
      this.download(
        'system/history/exportHistory',
        {
          ...queryParams
        },
        `history_${new Date().getTime()}.xls`
      )
    }
  }
}
</script>

<style scoped>
.handle-box {
  min-width: 1125px;
}

.handle-box * {
  float: left;
}

.handle-box span {
  line-height: 28px;
  margin-left: 30px;
}

.context {
  padding: 0;
  width: 100%;
  height: calc(100% - 60px);
  position: relative;
}
.context div {
  float: left;
}
#map {
  width: 100%;
  height: 100%;
}

.bottom_progress {
  position: absolute;
  width: 100%;
  height: 60px;
  bottom: 20px;
  display: grid;
  /* place-items: center;
   */
  place-content: end center;
}

>>> .vue-treeselect__control {
  width: 180px;
}

/deep/ .el-button--mini.is-circle {
  width: 36px;
  height: 36px;
}
</style>
